package com.auction.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.auction.service.ValidateCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
@Service
public class ValidateCodeServiceImpl implements ValidateCodeService {
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public Map<String, String> generateValidateCode() {
        // 通过工具类生成图片验证码
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(150, 48, 4, 20);
        // 验证码的值
        String codeValue = circleCaptcha.getCode();
        System.out.println("验证码为：" + codeValue);
        // 将图片进行 base64 编码，并返回
        String imageBase64 = circleCaptcha.getImageBase64();
        String key = UUID.randomUUID().toString().replaceAll("-", "");
        // 将验证码的值存入 Redis 并设置 5 分钟过期
        stringRedisTemplate.opsForValue().set("code:validate:" + key, codeValue, 5, TimeUnit.MINUTES);

        // 创建返回的 Map
        Map<String, String> codeMap = new HashMap<>();
        codeMap.put("key", key);
        codeMap.put("imageBase64", "data:image/png;base64," + imageBase64);

        return codeMap;
    }
}


